//
//  AudioTableCellPlayProgressView.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/11.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let playProgressColor = UIColor(fromRGB: 0xCBCBCB)

class AudioTableCellPlayProgressView: UIView {
  
  // MARK: - Private vars
  
  private var circleLayer: CAShapeLayer?
  private var progressLayer: CAShapeLayer?
  
  // MARK: - Private methods
  
  
  
  // MARK: - Public vars
  
  var progress: Float = 0 {
    didSet {
      setNeedsDisplay()
    }
  }
  
  // MARK: - Lifecycle
  
  override func willMove(toSuperview newSuperview: UIView?) {
    super.willMove(toSuperview: newSuperview)
    backgroundColor = .clear
    
    // draw cirlle
    if circleLayer == nil {
      let circlePath = UIBezierPath (
        arcCenter: CGPoint(x: width / 2, y: height / 2),
        radius: CGFloat(min(width, height) / 2),
        startAngle: CGFloat(0),
        endAngle: CGFloat(Double.pi * 2),
        clockwise: true
      )
      circleLayer = CAShapeLayer()
      circleLayer!.path = circlePath.cgPath
      circleLayer!.fillColor = UIColor.clear.cgColor
      circleLayer!.strokeColor = playProgressColor.cgColor
      circleLayer!.lineWidth = 1.0
      layer.addSublayer(circleLayer!)
    }
  }
  
  override func draw(_ rect: CGRect) {
    super.draw(rect)
    
    progressLayer?.removeFromSuperlayer()
    progressLayer = CAShapeLayer()
    
    let startAngle = CGFloat(-Double.pi / 2)
    let center = CGPoint(x: width / 2, y: height / 2)
    
    let path = UIBezierPath()
    path.addArc (
      withCenter: center,
      radius: CGFloat(min(width, height) / 2),
      startAngle: startAngle,
      endAngle: CGFloat(progress * Float(Double.pi * 2)) + startAngle,
      clockwise: true
    )
    path.addLine(to: center)
    
    progressLayer!.path = path.cgPath
    progressLayer!.fillColor = playProgressColor.cgColor
    layer.addSublayer(progressLayer!)
  }
  
  // MARK: - Public methods
  
}
